﻿namespace HynuIOTA.Web.Areas.Admin.Controllers
{
    using HynuIOTA.Web.Helpers;
    using HynuIOTA.Common.Attribute;
    using HynuIOTA.Helpers;
    using HynuIOTA.Web.Filters;
    using HynuIOTA.Web.Models;
    using System;
    using System.Data.Entity;
    using System.Linq;
    using System.Threading.Tasks;
    using System.Transactions;
    using System.Web.Mvc;
    using static HynuIOTA.Common.StringConst;

    public class ArticleController : BaseController
    {
        /// <summary>
        /// GET: Admin/Article/ArticleList
        /// 文章列表
        /// </summary>
        /// <returns></returns>
        public ActionResult ArticleList()
        {
            return View();
        }


        /// <summary>
        /// GET: Admin/Article/EditArticle
        /// 编辑文章
        /// </summary>
        /// <param name="Id"></param>
        /// <returns></returns>
        public async Task<ActionResult> EditArticle(int? Id)
        {
            if (Id == null)
            {
                return OpContext.JsMsg(MODEL_VALIDATE_ERROR);
            }

            var article = await OpContext.Service.BlogArticle.Where(a => a.Id == Id.Value).FirstOrDefaultAsync();
            if (article == null)
            {
                return OpContext.JsMsg(DATA_NOEXIST_ERROR);
            }

            ViewBag.article = article;
            return View();
        }

        /// <summary>
        /// GET: Admin/Article/ShowArticle
        /// 查看文章
        /// </summary>
        /// <param name="Id"></param>
        /// <returns></returns>
        public async Task<ActionResult> ShowArticle(int? Id)
        {
            if (Id == null)
            {
                return OpContext.JsMsg(MODEL_VALIDATE_ERROR);
            }

            var article = await OpContext.Service.BlogArticle.Where(a => a.Id == Id.Value).FirstOrDefaultAsync();
            if (article == null)
            {
                return OpContext.JsMsg(DATA_NOEXIST_ERROR);
            }

            ViewBag.article = article;
            return View();
        }

        /// <summary>
        /// PUT: Admin/Article/PutArticle
        /// 更改文章
        /// </summary>
        /// <param name="articleViewModel"></param>
        /// <returns></returns>
        [HttpPut]
        public async Task<ActionResult> PutArticle(PutArticleViewModel articleViewModel)
        {
            if (ModelState.IsValid == false)
            {
                return JsonMsgFail(MODEL_VALIDATE_ERROR);
            }

            var article = await OpContext.Service.BlogArticle.Where(a => a.Id == articleViewModel.Id)
                .FirstOrDefaultAsync();
            if (article == null)
            {
                return OpContext.JsonMsgFail(DATA_NOEXIST_ERROR);
            }
            
            Tools.SetValues(article,articleViewModel,ModelState.Keys.ToArray());
            var result = await OpContext.SaveChangesAsync();

            if (result != null)
            {
                return result;
            }
            // 刷新缓存
            OpContext.RefreshCacheDependency(CacheDependencyKeys.Article);
            return OpContext.JsonMsgOK(DATA_MODIFY_SUCCESS);
        }

        /// <summary>
        /// PUT: Admin/Article/PutArticlePass
        /// 审核通过文章
        /// </summary>
        /// <param name="Id"></param>
        /// <param name="ApprovedPass"></param>
        /// <param name="ApprovedInfo"></param>
        /// <returns></returns>
        [HttpPut]
        public async Task<ActionResult> PutArticlePass(int? Id,bool? ApprovedPass,string ApprovedInfo)
        {
            if (Id == null || ApprovedPass == null)
            {
                return OpContext.JsonMsgFail(MODEL_VALIDATE_ERROR);
            }

            var article = await OpContext.Service.BlogArticle.Where(a => a.Id == Id.Value).FirstOrDefaultAsync();
            if (article == null)
            {
                return OpContext.JsonMsgFail(DATA_NOEXIST_ERROR);
            }

            article.ApprovedPass = ApprovedPass.Value;
            article.ApprovedInfo = ApprovedInfo;

            var result = await OpContext.SaveChangesAsync();

            if (result != null)
            {
                return result;
            }
            // 刷新缓存
            OpContext.RefreshCacheDependency(CacheDependencyKeys.Article);
            return OpContext.JsonMsgOK(DATA_MODIFY_SUCCESS);
        }

        /// <summary>
        /// ANY: Admin/Article/GetArticlePage
        /// 获取文章列表
        /// </summary>
        /// <param name="page"></param>
        /// <param name="rows"></param>
        /// <returns></returns>
        [AjaxRequest]
        public async Task<ActionResult> GetArticlePage(int page = 1, int rows = int.MaxValue)
        {
            int total = await OpContext.Service.BlogArticle.Where(b => true).CountAsync();
            var pageList = await OpContext.Service.BlogArticle.Where(b => true).OrderBy(b => b.ApprovedPass).ThenByDescending(b => b.WriteTime).Skip((page - 1)*rows).Take(rows)
                .Select(r => new { r.Id, r.Title, Tags = r.Tags.Select(t => t.TagName), r.User.RealName, r.User.UserName, r.WriteTime, r.ApprovedPass, r.ApprovedInfo }).ToListAsync();

            return OpContext.JsonMsgOK(data: new { total , rows = pageList });
        }

        /// <summary>
        /// DELETE: Admin/Article/DeleteArticle
        /// 删除文章
        /// </summary>
        /// <param name="Id"></param>
        /// <returns></returns>
        [HttpDelete]
        [AjaxRequest]
        public async Task<ActionResult> DeleteArticle(int? Id)
        {
            if (Id == null)
            {
                return OpContext.JsonMsgFail(MODEL_VALIDATE_ERROR);
            }

            var article = await OpContext.Service.BlogArticle.Where(a => a.Id == Id.Value).FirstOrDefaultAsync();
            if (article == null)
            {
                return OpContext.JsonMsgFail(DATA_NOEXIST_ERROR);
            }

            using (TransactionScope transactionScope = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled))
            {
                try
                {
                    OpContext.Service.BlogComment.DeleteBy(c => c.BlogArticleId == article.Id);
                    OpContext.Service.BlogVisit.DeleteBy(v => v.BlogArticleId == article.Id);
                    article.Tags.Clear();
                    await OpContext.Service.SaveChangesAsync();

                    OpContext.Service.BlogArticle.Delete(article);
                    await OpContext.Service.SaveChangesAsync();

                    transactionScope.Complete();
                }
                catch (Exception ex)
                {
                    return OpContext.JsonMsgErr(ex.Message);
                }
            }

            OpContext.RefreshCacheDependency(CacheDependencyKeys.Article);
            return OpContext.JsonMsgOK(DATA_DELECT_SUCCESS);
        }
    }
}